package com.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.dropbox.client2.DropboxAPI.Entry;
import com.example.gcode.GCloudSingleton;
import com.gcloud.dto.GCloudFile;
import com.gcloud.persistance.SQLiteHandler;
import com.google.api.services.drive.model.File.Thumbnail;

//import com.google.api.services.drive.model.ParentReference;

public class GCloudUtil {

	public GCloudUtil() {

	}

	public static Context context;

	public static Context getContext() {
		return GCloudUtil.context;
	}

	public void setContext(Context context) {
		GCloudUtil.context = context;
	}

	public static List<GCloudFile> googleFilesToGCloudFiles(
			List<com.google.api.services.drive.model.File> googleFileList) {

		List<GCloudFile> files = new ArrayList<GCloudFile>();
		for (com.google.api.services.drive.model.File file : googleFileList) {

			files.add(new GCloudFile(file.getTitle(),
					file.getDescription() == null ? "" : file.getDescription(),
					file.getId(), file.getDownloadUrl() == null ? "" : file
							.getDownloadUrl(), Constants.GOOGLE, file
							.getMimeType(), file.getFileSize() == null ? 0
							: file.getFileSize()));
		}

		return files;
	}

	public static String getMimeTypeFromURI(String url) {
		String extension = MimeTypeMap.getFileExtensionFromUrl(url);
		Log.i("On utils", MimeTypeMap.getFileExtensionFromUrl(url));
		if (extension == null || extension.equals("")) {
			return getAlternativeMimeType(url);
		}
		MimeTypeMap mimeType = MimeTypeMap.getSingleton();
		return mimeType.getMimeTypeFromExtension(extension);
	}

	static Map<String, String> extensionMap = new HashMap<String, String>();

	private static void fillMymeTypes() {
		GCloudUtil.extensionMap.put(Constants.doc, Constants.adoc);
		GCloudUtil.extensionMap.put(Constants.xls, Constants.axls);
		GCloudUtil.extensionMap.put(Constants.xlsx, Constants.axlsx);
		GCloudUtil.extensionMap.put(Constants.xml, Constants.axml);
		GCloudUtil.extensionMap.put(Constants.ods, Constants.aods);
		GCloudUtil.extensionMap.put(Constants.csv, Constants.acsv);
		GCloudUtil.extensionMap.put(Constants.tmpl, Constants.atmpl);
		GCloudUtil.extensionMap.put(Constants.pdf, Constants.apdf);
		GCloudUtil.extensionMap.put(Constants.php, Constants.aphp);
		GCloudUtil.extensionMap.put(Constants.jpg, Constants.jpg);
		GCloudUtil.extensionMap.put(Constants.png, Constants.apng);
		GCloudUtil.extensionMap.put(Constants.gif, Constants.apng);
		GCloudUtil.extensionMap.put(Constants.bmp, Constants.abmp);
		GCloudUtil.extensionMap.put(Constants.txt, Constants.atxt);
		GCloudUtil.extensionMap.put(Constants.js, Constants.ajs);
		GCloudUtil.extensionMap.put(Constants.swf, Constants.aswf);
		GCloudUtil.extensionMap.put(Constants.mp3, Constants.amp3);
		GCloudUtil.extensionMap.put(Constants.zip, Constants.azip);
		GCloudUtil.extensionMap.put(Constants.rar, Constants.arar);
		GCloudUtil.extensionMap.put(Constants.tar, Constants.atar);
		GCloudUtil.extensionMap.put(Constants.arj, Constants.aarj);
		GCloudUtil.extensionMap.put(Constants.cab, Constants.acab);
		GCloudUtil.extensionMap.put(Constants.html, Constants.ahtml);
		GCloudUtil.extensionMap.put(Constants.htm, Constants.ahtml);
		GCloudUtil.extensionMap.put(Constants.defaults, Constants.adefaults);
		GCloudUtil.extensionMap.put(Constants.folder, Constants.afolder);
		GCloudUtil.extensionMap.put(Constants.xlsx, Constants.aoxlsx);
		GCloudUtil.extensionMap.put(Constants.oxltx, Constants.aoxltx);
		GCloudUtil.extensionMap.put(Constants.opotx, Constants.apotx);
		GCloudUtil.extensionMap.put(Constants.ppsx, Constants.appsx);
		GCloudUtil.extensionMap.put(Constants.pptx, Constants.pptx);
		GCloudUtil.extensionMap.put(Constants.sldx, Constants.asldx);
		GCloudUtil.extensionMap.put(Constants.docx, Constants.adocx);
		GCloudUtil.extensionMap.put(Constants.dotx, Constants.adotx);
		GCloudUtil.extensionMap.put(Constants.xlam, Constants.axlam);
		GCloudUtil.extensionMap.put(Constants.xlsb, Constants.axlsb);
	}

	private static String getAlternativeMimeType(String url) {
		fillMymeTypes();
		String extension = url.substring(url.length() - 3, url.length());
		extension = extension.trim();
		Log.i("Alternative extension: ", extension);
		// if(extensionMap.containsKey(extension)){

		return GCloudUtil.extensionMap.get(extension);
		// }
		// return "image/jpeg";

	}

	public static List<GCloudFile> dropBoxFilesToGCloudFiles(Entry entry) {
		List<GCloudFile> files = new ArrayList<GCloudFile>();
		for (Entry file : entry.contents) {
			files.add(new GCloudFile(file.fileName(), "", file.rev,
					file.mimeType, file.path == null ? "" : file.path,
					Constants.DROPBOX, 0, file.isDir));
		}
		return files;
	}

	public static GCloudFile getSelected(String key) {
		GCloudSingleton gCloudSingleton = GCloudSingleton.getInstance();
		for (GCloudFile file : gCloudSingleton.getFilesFromAllService()) {
			if (file.getKey().equalsIgnoreCase(key)) {
				return file;
			}
		}
		return null;
	}

	public static com.google.api.services.drive.model.File gCloudFileToGoogleDrive(
			GCloudFile file) {
		com.google.api.services.drive.model.File googleFile = new com.google.api.services.drive.model.File();
		googleFile.setId(file.getKey());
		googleFile.setDownloadUrl(file.getUri().getPath());
		googleFile.setDescription(file.getDescription());
		googleFile.setTitle(file.getName());
		googleFile.setMimeType(file.getMimeType());
		googleFile.setFileSize(file.getSize());
		return googleFile;
	}

	public static List<ContentValues> googleFileToContentValue(
			List<com.google.api.services.drive.model.File> googleFileList, String account) {
		List<ContentValues> contentValuesList = new ArrayList<ContentValues>();
		for (com.google.api.services.drive.model.File file : googleFileList) {

			ContentValues values = new ContentValues();
			values.put(Constants.FILE_KEY, file.getId());
			values.put(Constants.FILE_NAME, file.getTitle());
			values.put(Constants.FILE_DESCRIPTION, file.getDescription());
			values.put(Constants.FILE_MIMETYPE, file.getMimeType());
			values.put(Constants.FILE_ACCOUNT, account);
			values.put(Constants.FILE_URL, file.getDownloadUrl());
			values.put(Constants.FILE_SIZE, file.size());
			values.put(Constants.FILE_SERVICE, Constants.GOOGLE);
			values.put(
					Constants.FILE_IS_DIRECTORY,
					file.getMimeType().equals(
							"application/vnd.google-apps.folder") ? 1 : 0);
			try {
				Thumbnail imageFile = file.getThumbnail();
				if (imageFile != null) {
					String imageString = imageFile.getImage();
					values.put(Constants.FILE_THUMBNAIL, imageString);
					Log.i("GCloudUtil", "Thumbnail converted to string");
				}
			} catch (Exception e) {
				Log.i("GoogleDriveSync", "Imposible get thumbnail: "
						+ (e != null ? e : ""));
			}
			for (com.google.api.services.drive.model.ParentReference fileParents : file
					.getParents()) {
				values.put(Constants.FILE_IS_DIRECTORY,
						fileParents.getIsRoot() ? 1 : 0);
				values.put(Constants.FILE_PARENT, fileParents.getId());
				values.put(Constants.FILE_IS_ROOT, fileParents.getIsRoot() ? 1
						: 0);
			}
			values.put(Constants.FILE_FAVORITE, 0);
			contentValuesList.add(values);
		}
		sendToPersist(contentValuesList);
		return contentValuesList;
	}

	// private String listParents(List<ParentReference> list) {
	// String path = "";
	// for (ParentReference parentReference : list) {
	// path += parentReference.toString() + "; ";
	// }
	// return path;
	// }

	public static List<ContentValues> dropBoxToContentValue(Entry entry,
			String account) {
		List<ContentValues> contentValuesList = new ArrayList<ContentValues>();
		for (Entry file : entry.contents) {
			ContentValues values = new ContentValues();
			values.put(Constants.FILE_KEY, file.rev);
			values.put(Constants.FILE_NAME, file.fileName());
			values.put(Constants.FILE_DESCRIPTION, file.fileName());
			values.put(Constants.FILE_MIMETYPE,
					file.mimeType != null ? file.mimeType : Constants.afolder);
			values.put(Constants.FILE_ACCOUNT, account);
			values.put(Constants.FILE_URL, file.path);
			values.put(Constants.FILE_SIZE, file.size);
			values.put(Constants.FILE_IS_DIRECTORY, file.isDir);
			values.put(Constants.FILE_FAVORITE, 0);
			values.put(Constants.FILE_PARENT, file.parentPath());
			values.put(Constants.FILE_SERVICE, Constants.DROPBOX);
			contentValuesList.add(values);
		}
		sendToPersist(contentValuesList);
		return contentValuesList;
	}

	public static void sendToPersist(List<ContentValues> files) {
		// Log.i("GCloudUtil", "persist files");
		SQLiteHandler sqliteHandler = new SQLiteHandler(getContext(),
				Constants.GCLOUD, null, Constants.DB_VERSION);

		sqliteHandler.insertFiles(files);
	}

	public static boolean isEmpty(String input) {
		return input != null && !input.isEmpty() && !input.equals("");
	}

	public static String Message(String message, Object[] args) {
		return MessageFormat.format(message, args);
	}

	public static boolean equals(String arg0, String arg1) {
		return GCloudUtil.equals(arg0, arg1, false);
	}

	public static boolean equals(String arg0, String arg1, boolean caseSensitive) {
		if (caseSensitive) {
			return arg0.equals(arg1);
		}
		return arg0.equalsIgnoreCase(arg1);
	}

}
